//
//  ViewController.m
//  myhuibao
//
//  Created by lijun on 13-2-4.
//  Copyright (c) 2013年 myhuibao. All rights reserved.
//

#import "SmsViewController.h"
#import "AddressbookViewController.h"
#import "ASIHTTPRequest.h"
#import "ASIFormDataRequest.h"
#import "SBJson.h"
#import "config.h"
#import<QuartzCore/QuartzCore.h>
#import "RestaurantDetailViewController.h"

@interface SmsViewController ()

@end

@implementation SmsViewController
@synthesize mainView;
@synthesize lbTitle;
@synthesize tbNumber;
@synthesize tbContent;
@synthesize orderNo;
@synthesize content;
@synthesize ids;
@synthesize selectedNames;
@synthesize other;
- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    [self initDefault];
}
- (void)initDefault{
    tbContent.delegate=self;
    tbNumber.delegate = self;
    lbTitle.text = @"通知短信";//[NSString stringWithFormat:@"NO.%@订单提交成功。",orderNo ];
    tbContent.text = content;
    mainView.layer.cornerRadius=5;
    mainView.layer.borderWidth=1;
    mainView.layer.borderColor=[UIColor lightGrayColor].CGColor;
    ids = @"";
    selectedNames = @"";
    other = @"";
}
- (void)requestFailed:(ASIHTTPRequest *)request
{
    NSError *error = [request error];
    NSLog(@"%@",error);
}

- (void)viewDidUnload
{
    
    [self setMainView:nil];
    [self setTbNumber:nil];
    [self setTbContent:nil];
    [self setLbTitle:nil];
    [self setTbContent:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
        return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
    } else {
        return YES;
    }
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title=@"sms";
    }
    return self;
}
- (BOOL)textFieldShouldReturn:(UITextField *)theTextField {
    //    if (theTextField == self.textField) {
    [theTextField resignFirstResponder];
    //    }
    return YES;
}
- (IBAction)showAddressBook:(id)sender
{
    AddressbookViewController  *view = [[AddressbookViewController alloc] initWithNibName:@"AddressbookViewController" bundle:nil];
  
//    NSLog(@"%@",self.boxIds);
    view.delegate = self;
    view.selectedIds = self.ids;
    view.other= self.other;
    view.hidesBottomBarWhenPushed=YES;
	[self.navigationController pushViewController:view animated:YES];
}



- (IBAction)doBack:(id)sender {
//    [self.navigationController popViewControllerAnimated:YES];
    [self backToRestaurantDetail];
}

//提交
- (IBAction)doSave:(id)sender
{
    /*
    NSString* phones = tbNumber.text;
    NSRange range = [phones rangeOfString:@"，"];
    if (range.location != NSNotFound) {
        UIAlertView*alert = [[UIAlertView alloc]initWithTitle:@"提示"
                                                      message:@"请输入英文逗号。"
                                                     delegate:nil
                                            cancelButtonTitle:@"确定"
                                            otherButtonTitles:nil];
        [alert show];
        [alert release];
        return;
    }
    
//    NSLog(@"%@",phones);
    
    NSArray *ss = [phones componentsSeparatedByString:@","];
    NSString *mobiles = [ids copy];
    for(NSString *s in ss)
    {
        if ([s isEqualToString:@""]) {
            continue;
        }
        if([Config isMobileNumber:s])
        {
            mobiles = [mobiles stringByAppendingFormat:@"%@,",s];
        }else{
                NSRange range = [selectedNames rangeOfString:s];
                if (range.location == NSNotFound) {
                    UIAlertView*alert = [[UIAlertView alloc]initWithTitle:@"提示"
                                                                  message:@"请输入11位手机号码，并用逗号分开。"
                                                                 delegate:nil
                                                        cancelButtonTitle:@"确定"
                                                        otherButtonTitles:nil];
                    [alert show];
                    [alert release];
                    return;
                }
        }

    }*/
    NSString *mobiles = [ids copy];
    mobiles = [mobiles stringByAppendingString:other];
    if ([mobiles isEqualToString:@""]) {
        UIAlertView*alert = [[UIAlertView alloc]initWithTitle:@"提示"
                                                      message:@"短信接收号码不能为空。"
                                                     delegate:nil
                                            cancelButtonTitle:@"确定"
                                            otherButtonTitles:nil];
        [alert show];
        return;
    }
    //NSLog(@"%@",mobiles);
    NSURL *url = [NSURL URLWithString:url_inviteSMS];
    ASIFormDataRequest *request=[ASIFormDataRequest requestWithURL:url];
    int memberId = [[Config Instance] getMemberId];
    [request setPostValue:[NSString stringWithFormat:@"%d",memberId] forKey:@"memberID"];
    [request setPostValue:[[Config Instance] getPassword] forKey:@"password"];
    [request setPostValue:mobiles forKey:@"mobiles"];
    [request setPostValue:tbContent.text forKey:@"sms"];
    [request setPostValue:orderNo forKey:@"orderNO"];
    [request setShouldAttemptPersistentConnection:NO];
    [request startSynchronous];
    NSString *jsonStr = [request responseString];
    NSDictionary *dic = [jsonStr JSONValue];
   // NSLog(@"%@",dic);
    if([[dic valueForKey:@"status"] isEqualToString:@"SUCCESS"])
    {
        UIAlertView*alert = [[UIAlertView alloc]initWithTitle:@"提示"
                                                      message:@"短信提交成功，将在订单确认后发送。"
                                                     delegate:nil
                                            cancelButtonTitle:@"确定"
                                            otherButtonTitles:nil];
        [alert show];
//        [self.navigationController popViewControllerAnimated:YES];
        [self backToRestaurantDetail];
    }
}
//直接退回到详情页面
- (void) backToRestaurantDetail{
    RestaurantDetailViewController* vc;
    NSArray * vcs = [self.navigationController viewControllers];
    for (int i=0;i<vcs.count;i++) {
        if( [[vcs objectAtIndex:i] isKindOfClass:[RestaurantDetailViewController class]])
            vc = [vcs objectAtIndex:i];
        continue;
    }
    [self.navigationController popToViewController:vc animated:YES];
}
//实现传参协议的方法
#pragma mark UIViewPassValueDelegate mothod
- (void)passNames:(NSString *)names withIds:(NSString *) Ids withOther:(NSString *)others
{
    self.tbNumber.text = [names stringByAppendingString:others];
    selectedNames = [names copy];
    self.ids = Ids;
    self.other = [others copy];
//    NSLog(@"%@",boxIds);

}
#pragma mark - UITextView Delegate Methods
-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if ([text isEqualToString:@"\n"]) {
        [textView resignFirstResponder];
        return NO;
    }
    return YES;
}

@end
